package cl.tieba.core;

import io.dropwizard.Application;
import io.dropwizard.auth.basic.BasicAuthProvider;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import io.federecio.dropwizard.swagger.SwaggerDropwizard;

import java.util.EnumSet;

import javax.servlet.DispatcherType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cl.tieba.core.exception.dispose.TbExceptionMapper;
import cl.tieba.core.filter.TbFilter;
import cl.tieba.resource.CoreResource;
import cl.tieba.resource.SignResource;
import cl.tieba.resource.WateringResource;
import cl.tools.http.ContentType;

public class TiebaApplication extends Application<TiebaConfiguration> {
	private final SwaggerDropwizard swaggerDropwizard = new SwaggerDropwizard();

	private static final Logger LOGGER = LoggerFactory
			.getLogger(TiebaApplication.class);

	public static void main(String[] args) throws Exception {
		new TiebaApplication().run(args);
	}

	@Override
	public void initialize(Bootstrap<TiebaConfiguration> boot) {
		swaggerDropwizard.onInitialize(boot);
	}

	@Override
	public void run(TiebaConfiguration c, Environment e) throws Exception {
		LOGGER.info(c.getMessage());
		swaggerDropwizard.onRun(c, e, "localhost");

		r(e, new CoreResource());
		r(e, new SignResource());
		r(e, new WateringResource());
		// register filter
		e.servlets()
				.addFilter("TbFilter", new TbFilter())
				.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),
						true, "/*");
		//
		// register exception dispose
		r(e, new TbExceptionMapper());
		e.jersey().register(
				new BasicAuthProvider<Boolean>(new TiebaAuthenticator(),
						"Web Service Realm"));
	}

	private void r(Environment e, Object resource) {
		e.jersey().register(resource);
	}
}
